MySQL for Absolute Beginners




Why use MySQL?

There are many great DBMSs out there, including MySQL, PostgreSQL, SQLite, Oracle, and SQL Server, and all of them can be used for most web development purposes. That said, MySQL does have a few advantages for web developers compared to some other systems: It's open source, which means it's free for anyone to use and modify. It's widely available. MySQL can be installed on many different platforms, and it usually comes standard with most web hosting setups. It's easy to use. Setting up and working with MySQL databases is relatively straightforward. It works well with PHP. As of version 5.3, PHP has a native MySQL driver that is tightly coupled with the PHP engine, making it a good choice for PHP coders.

Each DBMS has its own strengths and weaknesses. For example, PostgreSQL is also open source, is very stable, and has a great community behind it. SQLite is extremely fast and self-contained (and is also free), while Oracle and SQL Server have a lot of enterprise-level features that make it a good choice for large organizations.

Installing MySQL

As I mentioned above, most web hosting accounts come with MySQL pre-installed. However, if you're developing websites using MySQL, you also want to have the MySQL server running on your own computer, so that you can create and test your databases and code without needing to upload files to your live server all the time. There are two main components to MySQL:

In addition, many MySQL installs include documentation, header files for developers, and the MySQL test suite. There are many ways to install the MySQL server and associated programs. Here are three ways you can do it:

If you want to get up and running as quickly and easily as possible, I'd personally recommend downloading and installing XAMPP. This LAMP/WAMP/MAMP package is available for Linux, Windows, Mac OS X and Solaris, and automatically installs and sets up Apache, MySQL, PHP and Perl on your computer. What's more, it's easy to uninstall everything later if you want to. To install XAMPP:
    Visit the XAMPP homepage and click the link for your operating system (Linux, Windows, Mac OS X or Solaris). Follow the steps on the page to download, install, start, and test the XAMPP system on your computer.

Other popular packages similar to XAMPP include WampServer and EasyPHP for Windows, and MAMP for Mac OS X.

XAMPP makes it easy to install a complete Apache, MySQL, PHP and Perl setup on Windows, Mac and Linux.

Issuing commands to MySQL

Assuming you've now installed and started your MySQL server using one of the above techniques, how do you interact with the server? When you installed the MySQL server, you also installed mysql, the MySQL Monitor. This is a command-line client program that you can use to connect to the server and issue commands. So let's try firing up the MySQL Monitor and see what it can do. Follow these two steps:
    Open a terminal window:

    Run the mysql program in the terminal window:

    The -u root parameter tells the MySQL Monitor to connect to the MySQL server using the root user, which is always available with MySQL. By default, MySQL's root user doesn't need a password. This is OK for a development setup on your computer, but a terrible idea for a live server! If you're installing MySQL on a live server, make sure you secure it properly. XAMPP also comes with some security scripts that can automatically make your XAMPP installation more secure.

Once the MySQL Monitor runs, you'll see something like this in your terminal window:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3893
Server version: 5.5.8 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> _
The last line, mysql>, is the MySQL prompt. This is where you type your commands to send to the MySQL server. Let's try out a couple of commands. Type the following at the mysql> prompt, then press Enter:
select now();
This tells MySQL to get the current date and time and display it. You'll see something like this appear:

+---------------------+
| now()               |
+---------------------+
| 2011-08-24 11:36:40 |
+---------------------+
1 row in set (0.00 sec)
Now try another command:
show databases;
This command lists all the MySQL databases on your computer. Since you've just installed MySQL, there will just be a few default databases, similar to the following:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)
Now that you know how to send commands to your MySQL server, you're ready to create your own database and start adding data to it. You'll do this in the following sections.

When you're finished with the MySQL Monitor, you can quit it by typing exit at the prompt and pressing Enter.

If you're not comfortable with the command line, there are other ways to administer MySQL and issue commands. MySQL Workbench is a free graphical app that can connect to any MySQL server and administer it. There's also the web-based phpMyAdmin, which is included in many LAMP/WAMP/MAMP packages.

Creating a database

Let's create a simple database for an imaginary book store. At your mysql> prompt, type the following and press Enter:
create database bookstore;
If all goes well, you'll see something like this:

Query OK, 1 row affected (0.05 sec)
MySQL has now created your database. You can check this by typing show databases again:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| bookstore         |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)
Congratulations — you've just created your first MySQL database!

Some SQL basics

All of the commands you've issued so far — select now(), show databases, and create database bookstore — are SQL statements. SQL, or Structured Query Language, is the language you use to communicate with most DBMSs, including MySQL. Using SQL, you can create and delete databases and tables; insert new data into tables; update data; delete data; and retrieve data. Statements that retrieve data from a database are also commonly called queries, hence the name "Structured Query Language". You'll use SQL in the rest of this tutorial as you create a table in your new database, add a record, and retrieve a record.

Creating a simple table

As with all relational databases, MySQL organizes its data in tables. A table holds one or more records of related data, in a similar way to an associative array in JavaScript or PHP. A table consists of: The easiest way to understand fields and records is to see how they look when laid out in a table. Let's set up a books table to hold books in our book store:
id title author price
1 The Grapes of Wrath John Steinbeck 12.99
2 Nineteen Eighty-Four George Orwell 8.99
3 The Wind-Up Bird Chronicle Haruki Murakami 7.99
The top row of the table holds the field names: id, title, author, and price. The next three rows are the three book records in our table. Each record has its own field values: for example, the first record's title field contains "The Grapes of Wrath", while the second record's title field contains "Nineteen Eighty-Four". Since a single column in a table holds all the different record values for a specific field, fields are also commonly known as columns. Similarly, the records in a table are commonly called rows. So how do you actually create this table in MySQL? To do this, you need to create a schema for the table. This is a text file containing a series of SQL statements that create the table and define the table's fields. Here's the schema — save it as a file called books.sql somewhere on your computer:

USE bookstore;
DROP TABLE IF EXISTS books;
CREATE TABLE books
(
  id              int unsigned NOT NULL auto_increment, # Unique ID for the record
  title           varchar(255) NOT NULL,                # Full title of the book
  author          varchar(255) NOT NULL,                # The author of the book
  price           decimal(10,2) NOT NULL,               # The price of the book
    PRIMARY KEY     (id)
);
Let's take a look at the SQL statements in this file and see what they do: Now that we've created our schema statements, we need to run them through MySQL to create the actual table. To do this, switch back to the MySQL Monitor and type the following command at the mysql> prompt:
source /path/to/books.sql
...where /path/to/books.sql is the full path to your books.sql file. (If you ran mysql in the same folder as your books.sql file then you can just type source books.sql.) You should see the following output in MySQL Monitor:

Database changed
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.10 sec)
To check that your books table was created, you can type show tables:

mysql> show tables;
+---------------------+
| Tables_in_bookstore |
+---------------------+
| books               |
+---------------------+
1 row in set (0.00 sec)
You can even inspect the table schema to make sure it's correct. To do this, use the explain command, like this:

mysql> explain books;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| title  | varchar(255)     | NO   |     | NULL    |                |
| author | varchar(255)     | NO   |     | NULL    |                |
| price  | decimal(10,2)    | NO   |     | NULL    |                |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

Adding records

You've now created a database called bookstore, and added a books table to it. Let's try adding a record to the books table. To add a record to a table, you use the SQL INSERT statement, passing in the record's field names and values. Type the following line in the MySQL Monitor to insert a book record into your table:
INSERT INTO books ( title, author, price )
  VALUES ( "The Grapes of Wrath", "John Steinbeck", 12.99 );
You should see the following output, indicating that MySQL has added the row to the table:

Query OK, 1 row affected (0.06 sec)
As you can see, we've used an INSERT statement to add the book "The Grapes of Wrath" to the table. We specified INTO books to tell MySQL which table to insert the record into, then listed the field names that we want to supply values for in parentheses, followed by the keyword VALUES, followed by the field values in the same order as the field names, again in parentheses. Notice that we haven't specified a value for the id field. Since it's an auto_increment field, MySQL generates the field value automatically. Let's add another couple of books to the table:

mysql> INSERT INTO books ( title, author, price )
  VALUES ( "Nineteen Eighty-Four", "George Orwell", 8.99 ),
         ( "The Wind-Up Bird Chronicle", "Haruki Murakami", 7.99 );
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0
As you can see, you can insert multiple rows at once by supplying multiple sets of field values, enclosed in parentheses and separated by commas.

Retrieving records

Card index
Now that we've added some records to the table, how can we retrieve them? This is where SQL queries come in. The SQL SELECT statement lets you retrieve one or more records from a table — or even multiple tables at once — based on criteria that you supply. The basic syntax is:
SELECT fieldNames FROM tableName [WHERE criteria]

There's a lot more to the SELECT statement than this, but we'll keep things simple in this tutorial! Let's try a basic SELECT query on our books table using the MySQL Monitor:


mysql> SELECT * FROM books;
+----+----------------------------+-----------------+-------+
| id | title                      | author          | price |
+----+----------------------------+-----------------+-------+
|  1 | The Grapes of Wrath        | John Steinbeck  | 12.99 |
|  2 | Nineteen Eighty-Four       | George Orwell   |  8.99 |
|  3 | The Wind-Up Bird Chronicle | Haruki Murakami |  7.99 |
+----+----------------------------+-----------------+-------+
3 rows in set (0.00 sec)
This SELECT query retrieves all fields (*) from the books table. Since we haven't supplied any additional criteria, the query retrieves all the records in the table, and displays the field values in the MySQL monitor.

As you can see, MySQL has auto-generated the values for the id field, beginning with 1. What if we want to retrieve just one record from the table, such as the book "Nineteen Eighty-Four"? To narrow down the selection, we can add a WHERE clause, like this:


mysql> SELECT * FROM books WHERE id = 2;
+----+----------------------+---------------+-------+
| id | title                | author        | price |
+----+----------------------+---------------+-------+
|  2 | Nineteen Eighty-Four | George Orwell |  8.99 |
+----+----------------------+---------------+-------+
1 row in set (0.00 sec)
As well as selecting by the id field, we can select by any other field we like:

mysql> SELECT * FROM books WHERE title = "Nineteen Eighty-Four";
+----+----------------------+---------------+-------+
| id | title                | author        | price |
+----+----------------------+---------------+-------+
|  2 | Nineteen Eighty-Four | George Orwell |  8.99 |
+----+----------------------+---------------+-------+
1 row in set (0.01 sec)
We can also use other operators, such as < (less than), > (greater than), and the boolean AND operator, to retrieve a range of records:

mysql> SELECT * FROM books WHERE price < 10 AND price > 5;
+----+----------------------------+-----------------+-------+
| id | title                      | author          | price |
+----+----------------------------+-----------------+-------+
|  2 | Nineteen Eighty-Four       | George Orwell   |  8.99 |
|  3 | The Wind-Up Bird Chronicle | Haruki Murakami |  7.99 |
+----+----------------------------+-----------------+-------+
2 rows in set (0.00 sec)
Finally, instead of retrieving all fields using *, we can specify just the field or fields we want to retrieve. Here's an example:

mysql> SELECT title, author FROM books;
+----------------------------+-----------------+
| title                      | author          |
+----------------------------+-----------------+
| The Grapes of Wrath        | John Steinbeck  |
| Nineteen Eighty-Four       | George Orwell   |
| The Wind-Up Bird Chronicle | Haruki Murakami |
+----------------------------+-----------------+
3 rows in set (0.00 sec)
As you can see, SELECT queries make it easy to retrieve just the records and fields you want from your table.

Summary

This tutorial has introduced you to databases in general, and MySQL in particular. You've covered the following topics: MySQL databases are a big topic, and there are lot more important areas to explore, including updating and deleting records; table relationships; normalization; joining tables; and grouping results. However, I hope you've found this article useful as a general introduction to MySQL. If you want to learn more, the MySQL manual has a decent tutorial section, including more details on using the MySQL Monitor, creating databases, and adding tables and data. It also includes some common queries that you can take and adapt for your own uses. You might also like to read my article Build a CMS in an Afternoon with PHP and MySQL to learn how to use PHP and MySQL together in practice.